import React, { useState, useEffect } from 'react'
import { Table, Button } from 'antd'
import axios from 'axios'
import { Tag,notification } from 'antd'
import {useNavigate} from 'react-router-dom'

export default function AuditList() {
    const navigator = useNavigate()

  const { username } = JSON.parse(localStorage.getItem('token'))
  const [dataSource, setdataSource] = useState([])

  useEffect(() => {
    getData()
  }, [])

  const getData = () => {
    axios(
      `/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`,
    ).then((res) => {
      setdataSource(res.data)
    })
  }
  //撤销
  const handleRervert = (item) => {
    axios.patch(`/news/${item.id}`,{
        auditState:0
    }).then(res=>{
        notification.info({
            message: `通知`,
            description:
              `您可以到草稿箱中查看您的新闻`,
            placement:"bottomRight"
        });
        getData()
    })
    
  }
  //发布
  const handlePublish = (item) => {
    axios.patch(`/news/${item.id}`,{
        "publishState": 2
    }).then(res=>{
        notification.info({
            message: `通知`,
            description:
              `您可以到草稿箱中查看您的新闻`,
            placement:"bottomRight"
        });

        setTimeout(()=>{
            navigator('/publish-manage/published')
        },2000)

    })
  }
  //更新
  const handleUpdate = (item) => {
    navigator('/news-manage/add',{state:{id:item.id}})
  }


  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '新闻分类',
      key: 'categoryId',
      render: (item) => item.category.title,
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        const colorList = ['', 'orange', 'green', 'red']
        const auditList = ['草稿箱', '审核中', '已通过', '未通过']
        return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
      },
    },
    {
      title: '操作',
      key: 'operate',
      render: (item) => {
        return (
          <div>
              {item.auditState ===1 && <Button  onClick={() => handleRervert(item)}>撤销</Button>}
              {item.auditState ===2 && <Button danger onClick={() => handlePublish(item)}>发布</Button>}
              {item.auditState ===3 && <Button type="primary" onClick={() => handleUpdate(item)}>更新</Button>}
          </div>
        )
      },
    },
  ]
  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 5,
        }}
      />
    </div>
  )
}
